import {fileURLToPath, URL} from 'node:url'

import {defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
import postCssPxToRem from "postcss-pxtorem"

// https://vitejs.dev/config/
export default defineConfig((env) => {
    const viteEnv = loadEnv(env.mode, process.cwd());
    return {
        base: viteEnv.VITE_BASE,
        plugins: [
            vue(),
            AutoImport({
                resolvers: [ElementPlusResolver(),IconsResolver({
                    prefix: 'Icon',
                }),],
            }),
            Components({
                // directoryAsNamespace: true,
                // deep: true,
                resolvers: [ElementPlusResolver(), IconsResolver(),],
            }),
            Icons({
                autoInstall: true,
                compiler: 'vue3'
            }),
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url))
            }
        },
        server: {
            host: '0.0.0.0',
            port: 8000,
            open: true,
            strictPort: true,
            proxy: {

                '/api': {
                    target: 'http://localhost:7890/',
                    changeOrigin: true, // 允许跨域
                    rewrite: (path) => path.replace('/api/', '/'),
                    ws: true
                },

            },
        },
        css: {
            postcss: {
                plugins: [
                    postCssPxToRem({
                        //根元素字体大小
                        rootValue: 16,
                        //匹配CSS中的属性，* 代表启用所有属性
                        propList: ['font-size'],
                        //转换成rem后保留的小数点位数
                        unitPrecision: 5,
                        //小于12px的样式不被替换成rem
                        minPixelValue: 12,
                        //忽略一些文件，不进行转换，比如我想忽略 依赖的UI框架
                        exclude: ['node_modules']
                    })
                ]
            },
            preprocessorOptions: {
                scss: {
                    additionalData: `@import "@/assets/variables.scss";`,
                    javascriptEnabled: true,
                },
            },
        },
        build: {
            outDir:'./dist',
            emptyOutDir: true,
            // 消除打包大小超过500kb警告
            chunkSizeWarningLimit: 2000,
            assetsDir: 'static/assets',
            rollupOptions: {
                output: {
                    chunkFileNames: 'static/js/[name]-[hash].js',
                    entryFileNames: 'static/js/[name]-[hash].js',
                    assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
                },
            },
        },
    }
})
